package com.example.administrator.pandanotes;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import org.litepal.LitePal;
import org.litepal.crud.DataSupport;

import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import static com.example.administrator.pandanotes.R.string.id;
/**
 * Created by 于博 on 2018-06-07.
 * 注册登录界面，具有注册登录功能
 * 根据提示输入账号密码即可，点击注册按钮进行注册，
 * 点击登录按钮进行登录。
 * 可以记住密码，方便下次登录
 */
public class LoginActivity extends AppCompatActivity {
    //变量***************************************************************************
    private Button btnLogin = null;
    private Button btnLoginRegister = null;
    private EditText eTLoginID = null;
    private EditText eTLoginPwd = null;
    private CheckBox cBPwd = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        LitePal.initialize(this);
        //初始化及绑定********************************************************************
        btnLogin = (Button) findViewById(R.id.btnLogin); //登录按钮
        btnLoginRegister = (Button) findViewById(R.id.btnLoginRegister);//注册按钮
        eTLoginID = (EditText) findViewById(R.id.eTLoginID); //用户id
        eTLoginPwd = (EditText) findViewById(R.id.eTLoginPwd);//用户密码
        cBPwd = (CheckBox)findViewById(R.id.cBPwd);//记住密码按钮
        //函数或事件****************************************************************
        List<User> users = DataSupport.where("user_flag=?","1").find(User.class);//找到记住密码的用户
        if (users.size()>0)//存在该用户
        {
            User user = users.get(0);//得到用户
            eTLoginID.setText(user.getUser_id());
            eTLoginPwd.setText(user.getUser_pwd());
            cBPwd.setChecked(true);//设置选中
        }
        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {          //登录按钮点击事件
                //获得值
                String UserID = eTLoginID.getText().toString();
                String UserPwd = eTLoginPwd.getText().toString();
                //异常处理
                if (TextUtils.isEmpty(UserID) || TextUtils.isEmpty(UserPwd))//账号或密码为空
                {
                    Toast.makeText(LoginActivity.this, "账号或密码为空", Toast.LENGTH_SHORT).show();
                } else {
                    List<User> users = DataSupport.where("user_id=? and user_pwd=?", UserID, UserPwd).find(User.class);
                    if (users.size() > 0) {
                        ProgressDialog progressDialog = new ProgressDialog(LoginActivity.this);
                        progressDialog.setMessage("loading...");
                        progressDialog.show();
                        User user = users.get(0);//得到当前用户
                        if(cBPwd.isChecked())    //记住密码
                        {
                            user.setUser_flag("1");
                            user.save();
                        }
                        else
                        {
                            user.setUser_flag("0");
                            user.save();
                        }
                        setCookies(user);        //保存到文件
                        try {
                            Thread.currentThread().sleep(2000);
                        }
                        catch(InterruptedException e)
                        {
                            e.printStackTrace();
                        }
                        Intent intent = new Intent(LoginActivity.this, MainActivity.class);//跳转
                        startActivity(intent);
                        Toast.makeText(LoginActivity.this, "登录成功！", Toast.LENGTH_SHORT).show();
                        finish();  //关闭当前页面
                    } else {
                        Toast.makeText(LoginActivity.this, "账号或密码错误", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
        btnLoginRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {   //注册按钮点击事件
                //获得值
                String UserID = eTLoginID.getText().toString();
                String UserPwd = eTLoginPwd.getText().toString();
                User user = new User();
                user.setUser_id(UserID);
                user.setUser_pwd(UserPwd);
                user.setUser_name("昵称");
                user.setUser_sex("男");
                user.setUser_signature("您的签名");
                user.setUser_flag("0");
                //审核账号、密码，进行异常处理
                if(UserID.length()<8||UserID.length()>16)
                {
                    Toast.makeText(LoginActivity.this, "账号为8-16位字符或数字组成", Toast.LENGTH_SHORT).show();
                }
                else if(UserPwd.length()<8||UserPwd.length()>16)
                {
                    Toast.makeText(LoginActivity.this, "密码为8-16位字符或数字组成", Toast.LENGTH_SHORT).show();
                }
                else {
                    List<User> users = DataSupport.where("user_id=?", UserID).find(User.class);
                    if (users.size() > 0) {//存在当前用户
                        Toast.makeText(LoginActivity.this, "注册失败！已有该账号！", Toast.LENGTH_SHORT).show();
                    }
                    else {
                        boolean b = user.save();
                        if (b)
                            Toast.makeText(LoginActivity.this, "注册成功！", Toast.LENGTH_SHORT).show();
                        else
                            Toast.makeText(LoginActivity.this, "未知错误！", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });

    }
    private static void setCookies(User user){//保存用户id函数
    String id = user.getUser_id();
    try {
        FileWriter writer = new FileWriter(Environment.getExternalStorageDirectory() + "/pandanotescookies.txt");
        writer.write(id);
        writer.close();
     } catch (IOException e) {
        e.printStackTrace();
     }
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exitBy2Click();
            return true;
            //调用双击退出函数
        }
        return super.onKeyDown(keyCode, event);
    }
    /**
     * 双击退出函数
     */
    private static Boolean isESC = false;

    private void exitBy2Click() {
        Timer tExit ;
        if (!isESC) {
            isESC = true; // 准备退出
            Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            tExit = new Timer();
            tExit.schedule(new TimerTask() {
                @Override
                public void run() {
                    isESC = false; // 取消退出
                }
            }, 2000); // 如果2秒钟内没有按下返回键，则启动定时器取消掉刚才执行的任务

        } else {
            System.exit(0);
        }
    }
}
